<template>
  <div>
    <page-layout>
      <a-row :gutter="[10, 10]">
        <a-col :span="24">
          <a-card>
            <footer-button :buttons="formState.buttons" />
            <a-form
              ref="formRef"
              :model="modelForm.data"
              :rules="formRules"
              :label-col="{ span: 6 }"
              :wrapperCol="{ span: 15 }"
            >
              <a-row>
                <a-col :span="8">
                  <a-form-item
                    :label="t('preferentialAllocation.label.preferentialName')"
                  >
                    <a-input v-model:value="modelForm.data.preName" maxlength="100"/>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item
                    :label="t('preferentialAllocation.label.offerStartTime')"
                  >
                    <a-date-picker
                      v-model:value="modelForm.data.preBtime"
                      style="width: 100%"
                      show-time
                      placeholder="请选择"
                      @change="onTimeChange($event, 'start')"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item
                    :label="t('preferentialAllocation.label.offerEndTime')"
                  >
                    <a-date-picker
                      v-model:value="modelForm.data.preEtime"
                      style="width: 100%"
                      show-time
                      placeholder="请选择"
                      @change="onTimeChange($event, 'end')"
                    />
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="8">
                  <a-form-item
                    :label="
                      t(
                        'preferentialAllocation.label.typesOfPreferentialCourses'
                      )
                    "
                  >
                    <a-select v-model:value="modelForm.data.courseType">
                      <a-select-option
                        v-for="(item, index) in dictLists.data[
                          dictEnum.COURSE_TYPE
                        ]"
                        :key="index"
                        :value="item.value"
                      >
                        {{ item.label || "" }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col> -->
                <a-col :span="8">
                  <a-form-item
                    :label="t('preferentialAllocation.label.enableDisable')"
                  >
                    <a-switch
                      v-model:checked="modelForm.data.preStatus"
                      :checkedValue="'1'"
                      :unCheckedValue="'0'"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item
                    :label="t('preferentialAllocation.label.preferenceType')"
                  >
                    <a-select v-model:value="modelForm.data.preType">
                      <a-select-option
                        v-for="(item, index) in dictLists.data[
                          dictEnum.PRE_TYPE
                        ]"
                        :key="index"
                        :value="(item.value)"
                      >
                        {{ item.label }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="8">
                  <a-form-item
                    v-if="modelForm.data.preType == 3"
                    :label="
                      t('preferentialAllocation.label.totalPriceCeilingAmount')
                    "
                  >
                    <a-input-number
                      style="width: 100%"
                      v-model:value="modelForm.data.maxAmt"
                      :min="0"
                      :max="10000000000"
                      :step="1"
                      :precision="2"
                    />
                  </a-form-item>
                </a-col> -->
                <!-- <a-col :span="3"></a-col> -->
                <a-col v-if="modelForm.data.preType == 1 || modelForm.data.preType == 3" :span="8">
                  <a-form-item
                    :label="
                      t('preferentialAllocation.label.preferentialAmount')
                    "
                  >
                    <a-input-number
                      style="width: 100%"
                      v-model:value="modelForm.data.preAmt"
                      :min="0"
                      :max="1000000000"
                      :step="1"
                      :precision="2"
                    />
                  </a-form-item>
                </a-col>
                <a-col v-if="modelForm.data.preType == 2" :span="24">
                  <a-form-item>
                    <div style="margin-left: 25px">
                      {{
                        t("preferentialAllocation.label.numberOfLadderCourses")
                      }}&nbsp;&nbsp;<a-button type="primary" @click="handleAdd"
                        >添加</a-button
                      >
                    </div>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-row
                    v-for="(item, index) in modelForm.data.policyLadderList"
                    :key="index"
                  >
                    <a-col :span="8">
                      <a-form-item
                        :label="
                          t(
                            'preferentialAllocation.label.numberOfCoursesStarted'
                          )
                        "
                      >
                        <a-input v-model:value="item.startNum" />
                      </a-form-item>
                    </a-col>
                    <a-col :span="7">
                      <a-form-item
                        :label="
                          t(
                            'preferentialAllocation.label.numberOfCoursesCompleted'
                          )
                        "
                      >
                        <a-input v-model:value="item.endNum" />
                      </a-form-item>
                    </a-col>
                    <a-col :span="7">
                      <a-form-item
                        :label="
                          t('preferentialAllocation.label.preferentialAmount')
                        "
                      >
                        <a-input-number
                          style="width: 100%"
                          v-model:value="item.preAmt"
                          :min="0"
                          :max="1000000000"
                          :step="1"
                          :precision="2"
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :span="2">
                      <a-button
                        style="margin-left: 20px"
                        type="danger"
                        @click="handleDel(index)"
                        >{{ t("button.delete") }}</a-button
                      >
                    </a-col>
                  </a-row>
                </a-col>
                <a-col :span="24">
                  <a-form-item>
                    <div style="margin-left: 25px">
                      {{ t("preferentialAllocation.label.conditionalRules") }}
                    </div>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item
                    :label="t('preferentialAllocation.label.chooseSchool')"
                  >
                    <a-input v-model:value="modelForm.data.schName" readonly>
                      <template #addonAfter>
                        <div
                          class="primary-color cursor-pointer"
                          @click="openDialog('schoolVisible')"
                        >
                          {{ t('button.select') }}
                        </div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item
                    :label="t('preferentialAllocation.label.project')"
                  >
                    <a-input v-model:value="modelForm.data.projectName" readonly>
                      <template #addonAfter>
                        <div
                          class="primary-color cursor-pointer"
                          @click="openDialog('projectVisible')"
                        >
                          {{ t('button.select') }}
                        </div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                
                <a-col :span="8">
                  <a-form-item
                    :label="
                      t('preferentialAllocation.label.disciplineCategory')
                    "
                  >
                    <a-input v-model:value="modelForm.data.subjectName" readonly>
                      <template #addonAfter>
                        <div
                          class="primary-color cursor-pointer"
                          @click="openDialog('subjectVisible')"
                        >
                          {{ t('button.select') }}
                        </div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="3"></a-col> -->
                <a-col :span="8">
                  <a-form-item
                    :label="t('preferentialAllocation.label.selectCourse')"
                  >
                    <a-input v-model:value="modelForm.data.courseName" readonly>
                      <template #addonAfter>
                        <div
                          class="primary-color cursor-pointer"
                          @click="openDialog('courseVisible')"
                        >
                          {{ t('button.select') }}
                        </div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                 <a-col :span="8">
                  <a-form-item label="选择学期" name="semesterName">
                    <a-input
                      class="pointer-input"
                      v-model:value="modelForm.data.semesterName"
                      readonly
                      placeholder="请选择"
                    >
                      <template #addonAfter>
                        <div
                          class="primary-color cursor-pointer"
                          @click="openDialog('semesterVisible')"
                        >
                          选择
                        </div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                
              </a-row>
            </a-form>
          </a-card>
        </a-col>
      </a-row>
    </page-layout>
    <school
      v-if="formState.schoolVisible"
      :visible="formState.schoolVisible"
      @submit="submitCom($event, 'school')"
      @close="closeCom"
    ></school>
    <subject
      v-if="formState.subjectVisible"
      :visible="formState.subjectVisible"
      @submit="submitCom($event, 'subject')"
      @close="closeCom"
    ></subject>
    <course
      v-if="formState.courseVisible"
      :visible="formState.courseVisible"
      :params="{ schId: modelForm.data.schId || undefined, schName: modelForm.data.schName || undefined }"
      @submit="submitCom($event, 'course')"
      @close="closeCom"
    ></course>
    <project
      v-if="formState.projectVisible"
      :visible="formState.projectVisible"
      :params="{ schId: modelForm.data.schId || undefined, schName: modelForm.data.schName || undefined }"
      @submit="submitCom($event, 'project')"
      @close="closeCom"
    ></project>
    <BasicTableModal
      v-model:visible="formState.semesterVisible"
      v-if="formState.semesterVisible"
      :columns="formState.columns"
      :fetchAjax="formState.api"
      :searchParams="formState.searchParams"
      :searchForm="formState.searchForm"
      :title="formState.title"
      @selectUniversity="
        value => selectItem(value)
      "
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRaw,
  ref,
  onMounted,
  onActivated,
  watch
} from "vue";
import { useI18n } from "vue-i18n";
import BasicTableModal from "@/component/basic-table-modal";
import dictEnum from "@/const/dict";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import { Form, message, modal } from "ant-design-vue";
import { save, update, details } from "@/api/module/preferential-allocation";
import { useRouter, useRoute } from "vue-router";
import { page as termPage } from "@/api/module/term-manage"; // 学期

import school from "./components/school.vue";
import subject from "./components/subject.vue";
import course from "./components/course.vue";
import project from "./components/project.vue";
import moment from "moment";
import mixin from '@/mixins'
const useForm = Form.useForm;
export default defineComponent({
  name: "preferential-allocation-add",
  components: {
    school,
    subject,
    course,
    project,
    BasicTableModal
  },
  setup() {
    const { returnRoute } = mixin.setup()
    const { t } = useI18n();
    const router = useRouter();
    const route = useRoute();
    const formState = reactive({
      buttons: [
        {
          name: "save",
          event: () => onSubmit(),
          type: "primary",
          code: "",
        },
        {
          name: "reset",
          event: () => handleReset(),
          code: "",
        },
      ],
      schoolVisible: false,
      courseVisible: false,
      subjectVisible: false,
      projectVisible: false,
      semesterVisible: false,

      api: termPage,
      type: "",
      title: '选择学期',
      columns: [
        { dataIndex: "semesterName", key: "semesterName", title: "学期名称" },
        { dataIndex: "createTime", key: "createTime", title: "创建时间" },
        {
          dataIndex: "id",
          key: "id",
          title: "学期id"
        }
      ],
      searchParams: {},
      searchForm: [
        { type: "input", key: "semesterName", label: "学期名称" },
      ],
    });

    const modelForm = reactive({
      data: {
        preYear: moment(new Date()).format('YYYY'),
        policyLadderList: [],
      },
    });
    watch(() => modelForm.data, (value) => {
      if (value && value.preType != 2) {
        formState.policyLadderList = []
      }
    }, { deep: true })
    const formRules = reactive({});
    const { resetFields, validate, validateInfos } = useForm(
      modelForm.data,
      formRules
    );
    const onSubmit = () => {
      formRef.value.validate().then(() => {
        let result = toRaw(modelForm.data);
        if (result.id) {
          update(result)
            .then((res) => {
              if (res.success) {
                message
                  .success({ content: "保存成功", duration: 1 })
                  .then(() => {
                    returnRoute()
                    formRef.value.resetFields();
                  });
              } else {
                message.warning({ content: "保存失败", duration: 1 });
              }
            })
            .catch((err) => {
              console.log("err: ", err);
              message.warning({ content: "保存失败", duration: 1 });
            });
        } else {
          save(result)
            .then((res) => {
              if (res.success) {
                message
                  .success({ content: "保存成功", duration: 1 })
                  .then(() => {
                    returnRoute()
                    formRef.value.resetFields();
                  });
              } else {
                message.warning({ content: "保存失败", duration: 1 });
              }
            })
            .catch((err) => {
              message.warning({ content: "保存失败", duration: 1 });
            });
        }
      });
    };

    const handleReset = () => {
      modelForm.data = {
        preYear: moment(new Date()).format('YYYY'),
        policyLadderList: [],
      };
      formRef.value.resetFields();
    };

    const handleAdd = () => {
      modelForm.data.policyLadderList.push({
        startNum: "",
        endNum: "",
        preAmt: "",
      });
    };
    const handleDel = (idx) => {
      modelForm.data.policyLadderList = modelForm.data.policyLadderList.filter(
        (item, index) => idx != index
      );
    };
    const openDialog = (value) => {
      formState[value] = true;
    };

    const submitCom = (e, type) => {
      switch (type) {
        case "school":
          modelForm.data.schName = e.schoolEnName;
          modelForm.data.schId = e.id;
          modelForm.data.courseId = '';
          modelForm.data.courseName = '';
          modelForm.data.projectName = '';
          modelForm.data.projectId = '';
          break;
        case "subject":
          modelForm.data.subjectId = e.id;
          modelForm.data.subjectName = e.disciplineName;
          break;
        case "course":
          modelForm.data.courseId = e.id;
          modelForm.data.courseName = e.courseName;
          break;
        case "project":
          modelForm.data.projectName = e.projectName;
          modelForm.data.projectId = e.id;
          break;
      }
    };
    const selectItem = (value) => {
      formState.semesterVisible = false
      modelForm.data.semesterName = value.semesterName;
      modelForm.data.semesterId = value.id;
    }
    const closeCom = (value) => {
      formState[value] = false;
    };
    const onTimeChange = (event, type) => {
      console.log("event, type: ", event, type);
      switch (type) {
        case "start":
          modelForm.data.preBtime = moment(event._d).format(
            "YYYY-MM-DD HH:mm:ss"
          );
          break;
        case "end":
          modelForm.data.preEtime = moment(event._d).format(
            "YYYY-MM-DD HH:mm:ss"
          );
          break;
      }
    };
    const handleChange = (event) => {
      console.log("event, type: ", event);
    };
    const dictLists = reactive({
      data: {},
    });

    const loading = ref(false);
    const formRef = ref();
    // 获取详情
    const getDetails = (id) => {
      if (!id) return;
      return details({ id }).then((res) => {
        if (res.success) {
          modelForm.data = reactive({
            ...modelForm.data,
            ...res.data,
          });
          modelForm.data.preBtime = moment(modelForm.data.preBtime).format(
            "YYYY-MM-DD HH:mm:ss"
          );
          modelForm.data.preEtime = moment(modelForm.data.preEtime).format(
            "YYYY-MM-DD HH:mm:ss"
          );
          modelForm.data.preYear = modelForm.data.preYear.toString();
        }
      });
    };
    const panelChange = (value, model) => {
      modelForm.data.preYear = moment(value._d).format('YYYY')
    };
    onActivated(() => {
      const result = route.query;
      if (result && result.id) {
        getDetails(result.id);
      } else {
        modelForm.data = {
          policyLadderList: [],
        };
      }
    });
    
    onMounted(async () => {
      dictLists.data = await getDictByCodesReturnObj([
        dictEnum.COURSE_TYPE, // 课程类型
        dictEnum.PRE_TYPE, // 优惠类型
        dictEnum.QUARTER, // 季度
        dictEnum.YEAR, // 年份
        dictEnum.SEMESTER_PERIOD, // 学期时段
        dictEnum.CREDITS, // 学分
      ]);
    });
    return {
      t,
      labelCol: {
        span: 9,
      },
      formState,
      modelForm,
      formRules,
      formRef,
      onSubmit,
      handleReset,
      handleChange,
      loading,
      onTimeChange,
      handleAdd,
      handleDel,
      openDialog,
      dictEnum,
      dictLists,
      submitCom,
      selectItem,
      closeCom,
      resetFields,
      validateInfos,
      panelChange,
    };
  },
});
</script>

<style lang="less" scoped>
.upload-title {
  font-size: 14px;
  color: #b7b7b7;
}
</style>
